import { isString } from '@tarojs/shared';
import { MessagePluginManager } from '.';
import { Message } from '..';

import { MessageInfo, SendApiResult, SendParams } from '../type';

export class AiImcPlugin implements MessagePluginManager {
    isManual: boolean;
    name: string;
    extInfo: SendParams;
    content: string;
    constructor() {
        this.name = 'AiImcPlugin';
        this.isManual = false;
        this.extInfo = {};
        this.content = '';
    }

    startSend(params: SendParams) {
        const {
            MsgType: msgType,
            Event: event,
            ExtInfo: extInfo,
            Content: content,
            ...rest
        } = params;
        if (msgType === 'event' && event === 'transfer_manual') {
            this.content = content || '';
            this.isManual = true;
            this.extInfo = extInfo || {};
        }
        return { MsgType: msgType, Event: event, ExtInfo: extInfo, ...rest };
    }
    afterSend(response: [0 | 1, SendApiResult], context: Message) {
        const [err, data] = response;
        if (!err && data && this.isManual) {
            context.dispatchSend(
                {
                    Content: this.content,
                    ExtInfo: {
                        ...this.extInfo,
                        infoType: 'scene-reminder'
                    }
                },
                ['afterSendAsync']
            );
            this.isManual = false;
        }
    }
    beforeReceive(info: MessageInfo) {
        if (info && isString(info.Content) && info.Content === this.content) {
            return false;
        }
        return info;
    }
}
